<?php
//session_start();
//require_once('sql.php');

class login extends table
{
    //private $table;

    /**
    * Make the logout.<p>
    * Clean the session
    */
    public function logout()
    {
        unset($_SESSION['loginuser']['user']);
        unset($_SESSION['loginuser']['username']);
        unset($_SESSION['loginuser']['class']);
    }

    /**
    * Creates the PDO Connection and the table...
    *
    */
    public function login($db)
    {
        parent::table('login', NULL, $db);
        $this->addColumn('login'     , 'varchar(10) NOT NULL PRIMARY KEY');
        $this->addColumn('passwd'    , 'varchar(10) NOT NULL');
        $this->addColumn('username'  , 'varchar(255)');
        $this->addColumn('email'     , 'varchar(255)');
        $this->addColumn('count'     , 'integer');
        $this->addColumn('lastIp'    , 'varchar(15)');
        $this->addColumn('class'     , 'varchar(10)');
        $this->addColumn('lastLogin' , 'timestamp');
        $this->addColumn('createDate', 'timestamp');
        $this->clearWhere();
        $result = $this->db->query($this->create());
    }

	/**
	 * Make a login.
	 *
	 * @param 	$user		the user name
	 * @param 	$password	the user password
	 *
	 */
	public function connect($user, $password)
	{
        //var_dump($user, $password);
        if ( $user != '' && $user != NULL && $password != '' && $password != NULL)
        {
        	$this->clearWhere();
        	$this->addWhere("login  ="  , $user);
        	$this->addWhere("passwd ="  , $password);
            $result = $this->db->query( $this->select() );
            if ($result)
            {
                foreach ($result as $row)
                {
                    if ($row['login'] == '')
                    {
                        unset($_SESSION['loginuser']['user']);
                        return false;
                    }
                    else
                    {
                        $_SESSION['loginuser']['user']       = $row['login'];
                        $_SESSION['loginuser']['username']   = $row['username'];
                        $_SESSION['loginuser']['class']      = $row['class'];
                        $this->clearWhere();
                        $values['count']                     = $row['count']+1;
                        $values['ip']                        = $_SERVER['REMOTE_ADDR'];
                        $data['createDate']                 = date('Y-m-d H:m:s');
                        $this->addWhere('login=',$row['login']);
                        $result2 = $this->db->exec( $this->update($values) );
                        return true;
                    }
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            $this->logout();
            return false;
        }
	}

	/**
	 * Returns the logged user name.
	 *
	 * @return the logged user name.
	 */
	function getUser()
	{
		return $_SESSION['loginuser']['user'];
	}

    /**
     * Returns the logged user name (Complete).
     *
     * @return the logged user name (Complete).
     */
    function getUserName()
    {
        if ( $_SESSION['loginuser']['username'] == '')
        {
            return $_SESSION['loginuser']['user'];
        }
        else
        {
            return $_SESSION['loginuser']['username'];
        }
    }

    /**
     * Returns the logged user class
     *
     * @return the logged user class.
     */
    function getClass()
    {
        return $_SESSION['loginuser']['class'];
    }

	/**
	 * Verify if user is logged.
	 *
	 * @return true or false, if user is logged.
	 *
	 */
	function isLogged()
	{
		if ( is_object( $_SESSION['loginuser'] ) )
		{
			return true;
		}
		else
		{
			$temp = $_SESSION['loginuser']['user'];
			if ( $temp != "" )
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}

    /**
    * This function is to be used when user chooses to change his data
    */
    function updateLoggedUser($username, $passwd, $repasswd)
    {
        //TODO EMAIL
        if ( ($passwd !='' && $passwd != null) & ($passwd == $repasswd) )
        {
            $values['passwd']       = $passwd;
        }

        if ($username !='' && $username !=null)
        {
            $values['username']     			 = $username;
            $_SESSION['loginuser']['username']   = $username;
        }

        if ($values)
        {
            $this->table->clearWhere();
            $this->table->addWhere('login=' , $this->getUser() );
            $sql = $this->table->update($values);
            return $result = $this->db->exec( $sql );
        }
        else
        {
            return false;
        }
    }

    /**
    * Insert a new user in Login
    *
    */
    function createUser($data)
    {
        //verify if is admin
        if ($this->getClass() =='admin')
        {
            $temp = $this->getUserData($data['login']);
            $mode = 'ins';

            if ($temp)
            {
                foreach ($temp as $row)
                {
                    if ( $row['login'])
                    {
                        $mode = 'up';
                    }
                    else
                    {
                        $mode = 'ins';
                    }
                }
            }
            if ($data['login'] && $data['passwd'] && $data['class'])
            {
                if ($mode == 'ins')
                {
                    //define the create date
                    echo "insert";
                    //$data['createDate'] = date('Y-m-d H:m:s');
                    $sql = $this->insert($data);
                    echo $sql;
                    
                }
                else
                {
                    $sql = $this->update($data);
                }

                return $result = $this->db->exec( $sql );
            }
            else
            {
                return false;
            }
        }
        else
        {
            echo "You not have admin right";
            return false;
        }
    }

    /**
    * List all user registered.
    *
    */
    function listAll()
    {
        if ($this->getClass() =='admin')
        {
            $this->clearWhere();
            $sql = $this->select();
            $result = $this->db->query($sql);
            return $result;
        }
        else
        {
            return false;
        }
    }

    /**
    * Return all Data of an Specified User
    *
    */
    function getUserData($login)
    {
        if ($login)
        {
            $this->clearWhere();
            $this->addWhere("login  ="  , $login);
            return $this->db->query( $this->select() );
        }
        else
        {
            return false;
        }
    }

    /**
    * Remove an User, passing it Id.
    *
    */
    function removeUser($login)
    {
        $this->clearWhere();
        $this->addWhere("login  ="  , $login);
        return $this->db->query( $this->delete() );
    }
}
?>
